﻿using MarkdownWeb.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MarkdownWeb.Controllers
{
    public class EditController : Controller
    {
        // GET: Edit
        public ActionResult Index(string title)
        {
            if(string.IsNullOrEmpty(title))
            {
                return new RedirectResult("/首页");
            }
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WikiContentContext>());
            var context = new WikiContentContext();
            var content = context.Wikis.FirstOrDefault(c => c.Title == title);
            if(content == null)
            {
                return new RedirectResult($"/Create/Index?title={title}");
            }
            ViewData["content"] = content;
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public JsonResult Save(FormCollection form)
        {
            JsonResult ret = new JsonResult();
            try
            {
                var data = form["data"];
                var title = form["title"];
                Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WikiContentContext>());
                var context = new WikiContentContext();
                var content = context.Wikis.FirstOrDefault(w => w.Title == title);
                if (content == null)
                {
                    content = new WikiContent();
                    content.Title = data;
                    content.CreateTime = DateTime.Now;
                    content.Creater = Session["name"] as string;
                    content.LastEditTime = content.CreateTime;
                    context.Wikis.Add(content);
                }
                content.Content = data;
                context.SaveChanges();
                ret.Data = new { result="ok",title=title};
            }
            catch(Exception e)
            {
                ret.Data = new { result = e.Message };
            }
            return ret;
        }
    }
}